#include "client.h"
#include "my_header.h"

int uRegister(int sockfd ,char* uPass){
    int result = 0;// 接收服务端发来的结果
    char username[100] = {0};
    char password[100] = {0};
    train_t train;
    bzero(&train,sizeof(train));

    printf("Please enter user name:\n");
    scanf("%s",username);
    printf("Please enter password\n");
    scanf("%s",password);

    // 发送火车
    train.type = REGISTER;
    sprintf(train.data,"%s!%s",username,password);
    DEBUG_PRINT("train.data = %s\n",train.data);
    train.length = strlen(train.data);
    send(sockfd,&train,sizeof(train.length) + sizeof(train.type) + train.length,0);
    DEBUG_PRINT("注册的用户名和密码已发送\n");

    // 接收盐值并发送密文
    char crptpasswd[107] = {0};
    char salt[21] = {0};
    DEBUG_PRINT("before recvn\n");
    recvn(sockfd,salt,20);
    DEBUG_PRINT("salt = %s\n",salt);

    // 计算密文并发送
    strncpy(crptpasswd,crypt(password,salt),106);
    bzero(&train,sizeof(train));
    train.length = strlen(crptpasswd);
    strcpy(train.data,crptpasswd);
    send(sockfd,&train,sizeof(train.type)+sizeof(train.length) + train.length,MSG_NOSIGNAL);
    DEBUG_PRINT("注册的密文已发送\n");

    recvn(sockfd,&result,sizeof(result));
    DEBUG_PRINT("注册的结果是result = %d\n",result);

    return result;
}

int uLogin(int sockfd, char *uName,char *uPass){
    int result = 0;
    char username[100] = {0};
    char password[100] = {0};
    printf("Please enter username:\n");
    scanf("%s",username);
    train_t train;
    bzero(&train,sizeof(train));
    while(1){
        printf("Please enter your password:\n");
        scanf("%s",password);
        sprintf(uPass,"%s",password);
        train.type = LOGIN;
        sprintf(train.data,"%s!%s",username,password);
        DEBUG_PRINT("train.data = %s\n",train.data);
        train.length = strlen(train.data);
        send(sockfd,&train,sizeof(train.length) + sizeof(train.type) + train.length,0);

        // 接收查看用户是否存在
        /* recvn(sockfd,&result,sizeof(result)); */

        // 用户未注册
        //if(result == 2){
        //    break;
        //}

        // 用户已注册
        char crptpasswd[107] = {0};
        char salt[21] = {0};
        recvn(sockfd,salt,20);

        // 计算密文发送
        strncpy(crptpasswd,crypt(password,salt),106);
        DEBUG_PRINT("crptpasswd = %s\n",crptpasswd);
        bzero(&train,sizeof(train));
        train.length = strlen(crptpasswd);
        strcpy(train.data,crptpasswd);
        send(sockfd,&train,sizeof(train.length)+sizeof(train.type)+train.length,MSG_NOSIGNAL);
        DEBUG_PRINT("登录密文已发送\n");

        // 验收结果
        recvn(sockfd,&result,sizeof(result));
        DEBUG_PRINT("result = %d\n",result);
        if(result == 1){
            strcpy(uName,username);
            break;
        }
        else{
            printf("Password is worng!\n");
        }
    }
    return result;
}
